package etnorservice.etnor_service.service;

import etnorservice.etnor_service.domain.po.MenuItem;
import etnorservice.etnor_service.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * @Author: cc
 * @Date: 2024/10/17/13:28
 **/
@Service
public class MenuService {
    @Autowired
    MenuMapper menuMapper;
    // 构建菜单树
    public List<MenuItem> buildMenuTree() {
        // 获取所有顶层菜单
        List<MenuItem> topMenus = menuMapper.findAllNodeMenu();

        // 为每个顶层菜单项添加子菜单
        for (MenuItem menuItem : topMenus) {
            addChildren(menuItem);
        }

        return topMenus;
    }

    // 递归添加子菜单
    private void addChildren(MenuItem menuItem) {
        List<MenuItem> children = menuMapper.findChirendNode(menuItem.getId() + "");
        if (children != null && !children.isEmpty()) {
            menuItem.setChildren(children);
            for (MenuItem child : children) {
                addChildren(child);
            }
        }
    }
}
